package com.hsxxherp.simplify.ip2region;

import com.hsxxherp.simplify.framework.exception.BusinessException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lionsoul.ip2region.xdb.Searcher;

/**
 * Ip2Region 服务
 *
 * @author Mark·虎克 (2486970363@qq.com)
 */
public class Ip2Region {
    private static final Log log = LogFactory.getLog(Ip2Region.class);

    private static final int IP_REGION_PARTS_LENGTH = 5;

    private final Searcher searcher;

    public Ip2Region(Searcher searcher) {
        this.searcher = searcher;
        log.debug("Ip2Region constructor");
    }

    public IpRegionInfo getRegion(String ip) {
        try {
            String region = searcher.search(ip);
            if (region != null) {
                String[] parts = region.split("\\|");
                if (parts.length == IP_REGION_PARTS_LENGTH) {
                    String country = parts[0];
                    String regionStr = parts[1];
                    String province = parts[2];
                    String city = parts[3];
                    String isp = parts[4];
                    return new IpRegionInfo(country, regionStr, province, city, isp);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(String.format("ip地址解析错误：{%S}",ip),e);
        }
        return null;
    }
}